package com.duan.laugh.sms.ali.config;

import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.profile.DefaultProfile;
import com.duan.laugh.common.core.annotation.BeanAlias;
import com.duan.laugh.sms.core.SmsAccount;
import com.duan.laugh.sms.core.SmsChannel;
import com.duan.laugh.sms.core.SmsRequest;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

/**
 * 阿里云短信渠道
 *
 * @author duanjw
 */
@Service
@Slf4j
@BeanAlias("2")
public class AliSmsChannelImpl implements SmsChannel {
    /**
     * 阿里云短信client
     */
    private IAcsClient iAcsClient;

    /**
     * 初始化客户端
     *
     * @param smsAccount
     */
    private void initClient(SmsAccount smsAccount) {
        // 创建DefaultAcsClient实例并初始化
        DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou", smsAccount.getAccess(), smsAccount.getSecret());
        iAcsClient = new DefaultAcsClient(profile);
    }

    /**
     * 阿里发送短信
     *
     * @param smsAccount
     * @param smsRequest
     * @return
     */
    @Override
    @SneakyThrows
    public boolean sendSms(SmsAccount smsAccount, SmsRequest smsRequest) {
        initClient(smsAccount);
        SendSmsRequest request = new SendSmsRequest();
        //必填:待发送手机号
        request.setPhoneNumbers(smsRequest.getMobile());
        //必填:短信签名-可在短信控制台中找到
        request.setSignName(smsRequest.getSignName());
        //必填:短信模板-可在短信控制台中找到
        request.setTemplateCode(smsRequest.getTemplate());
        //可选:模板中的变量替换JSON串,如模板内容为"亲爱的${value},您的验证码为${code}"
        String context = smsRequest.getContext();
        request.setTemplateParam(context);
        request.setOutId(smsRequest.getMobile());
        log.info("调用阿里云的发送短信");
        final SendSmsResponse acsResponse = iAcsClient.getAcsResponse(request);
        log.info("阿里云发送短信返回code码：【{}】，消息：【{}】", acsResponse.getCode(), acsResponse.getMessage());
        return true;
    }
}
